package model

import (
	"database/sql"
	"fmt"

	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ PropertyModel = (*customPropertyModel)(nil)

type (
	// PropertyModel is an interface to be customized, add more methods here,
	// and implement the added methods in customPropertyModel.
	PropertyModel interface {
		propertyModel
		TxAdjustStock(tx *sql.Tx, id int64, delta int) (sql.Result, error)
	}

	customPropertyModel struct {
		*defaultPropertyModel
	}
)

// NewPropertyModel returns a model for the database table.
func NewPropertyModel(conn sqlx.SqlConn, c cache.CacheConf) PropertyModel {
	return &customPropertyModel{
		defaultPropertyModel: newPropertyModel(conn, c),
	}
}
func (m *defaultPropertyModel) TxAdjustStock(tx *sql.Tx, id int64, delta int) (sql.Result, error) {
	propertyKey := fmt.Sprintf("%s%v", cachePropertyIdPrefix, id)
	return m.Exec(func(conn sqlx.SqlConn) (outcome sql.Result, err error) {
		deliberate := fmt.Sprintf("update %s set stock=stock + ? where stock >= -? and id = ?", m.table)
		return tx.Exec(deliberate, delta, delta, id)
	}, propertyKey)
}
